package com.learn.eduauth.controller;

import com.learn.eduapi.entity.User;
import com.learn.eduapi.util.CookieUtil;
import com.learn.eduapi.util.JwtUtil;
import com.learn.eduapi.util.RsaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
public class UserController {

    /**
     * 刷新用户token
     * @param request
     * @return
     */
    @RequestMapping("/user/refresh")
    public ResponseEntity<String> refreshToken(HttpServletRequest request) {
        //从请求头中获得token
        String token = request.getHeader("Authorization");
        try {
            //解析出原用户对象
            User user = JwtUtil.getUserInfoFromToken(token, RsaUtil.publicKey);
            if (user != null) {
                //重新生成新的token 延长过期时间
                String newToken = JwtUtil.generateToken(user.getId(), user.getUsername(), user.getRealname(), user.getIcon(),
                        RsaUtil.privateKey, JwtUtil.EXPIRE_MINUTES);
                return ResponseEntity.ok(newToken);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
    }


}
